<template>
  <div class="view-container">
    <card-box class="org-tree">
      <template #header>
        <el-button @click="foldAll" icon="ZoomOut" text />
        <span>组织</span>
        <el-button @click="expandAll" icon="ZoomIn" text />
      </template>

      <template #search>
        <el-input v-model="filterText" placeholder="输入组织名称进行过滤" clearable />
      </template>

      <el-tree :node-key="treeOptions.tree.nodeKey" :ref="treeOptions.tree.ref" :expand-on-click-node="false"
        :highlight-current="true" :data="tree.data" :props="treeOptions.tree.propConfig"
        :filter-node-method="filterTreeNode" @node-click="clickNode" default-expand-all />
    </card-box>

    <b-table>
      <!--  搜索栏  -->
      <template #query>
        <query-form>
          <el-form :ref="options.queryForm.ref" :model="queryModel" :inline="true" label-position="left">
            <el-form-item label="上级组织" prop="parentId">
              <el-tree-select ref="menuTreeRef" :node-key="treeOptions.tree.nodeKey" v-model="queryModel.parentId"
                :props="treeOptions.tree.propConfig" :data="tree.data" :filter-node-method="filterTreeNode" filterable
                default-expand-all check-strictly clearable />
            </el-form-item>

            <el-form-item label="组织编码" prop="code">
              <el-input v-model="queryModel.code" @keyup.enter="handleQuery" placeholder="请输入组织编码" clearable />
            </el-form-item>

            <el-form-item label="组织名称" prop="name">
              <el-input v-model="queryModel.name" @keyup.enter="handleQuery" placeholder="请输入组织名称" clearable />
            </el-form-item>

            <el-form-item label="组织状态" prop="state">
              <el-radio-group v-model="queryModel.state">
                <el-radio :label="undefined">所有</el-radio>
                <el-radio :label="0">禁用</el-radio>
                <el-radio :label="1">启用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>

          <template #footer>
            <el-button icon="RefreshLeft" @click="resetQuery" size="small" auto-insert-space>重置</el-button>
            <el-button type="primary" icon="Search" v-loading="loading.query" @click="handleQuery" size="small"
              auto-insert-space>
              搜索
            </el-button>
          </template>
        </query-form>
      </template>

      <!--  按钮栏  -->
      <template #toolbar>
        <toolbar :tableModel="tableModel" :options="options" @fetchTableData="fetchTableData"
          @pageNumChange="pageNumChange" @pageSizeChange="pageSizeChange" @saveColumnSetting="saveColumnSetting"
          @resetColumn="resetColumnSetting">
          <toolbar-item v-hasPerm="'org:insert'">
            <el-button @click="handleAdd" type="success" icon="Plus" size="small" plain auto-insert-space>
              新增
            </el-button>
          </toolbar-item>

          <toolbar-item v-hasPerm="'org:edit'">
            <el-button @click="handleEdit(tableModel.selectedRow[0])" :disabled="disabled.edit" type="primary"
              icon="Edit" size="small" plain auto-insert-space>
              编辑
            </el-button>
          </toolbar-item>

          <toolbar-item v-hasPerm="'org:export'">
            <export-excel @export-all="handleExport(true)" @export-current="handleExport(false)" />
          </toolbar-item>

          <toolbar-item v-hasPerm="'org:upload'">
            <upload-excel :show="upload.show" :limit="upload.limit" :headers="upload.headers" :action="upload.action"
              :strategy="upload.param" @handleFileUploadProgress="handleFileUploadProgress"
              @handleFileSuccess="handleFileSuccess" @closeUpload="closeUpload" @submitUpload="submitUpload"
              @handleUpload="handleUpload" />
          </toolbar-item>

          <toolbar-item v-hasPerm="'org:delete'">
            <el-button @click="handleDelete()" v-loading="loading.delete" :disabled="disabled.delete" type="danger"
              icon="Delete" size="small" plain auto-insert-space>
              删除
            </el-button>
          </toolbar-item>
        </toolbar>
      </template>

      <!--  表格栏  -->
      <el-table :ref="options.table.ref" v-loading="loading.table" :data="tableModel.data"
        :header-cell-class-name="handleHeaderCellClass" @sort-change="handleSortChange"
        @selection-change="handleSelectionChange" @current-change="clickTableRow" @row-dblclick="handleEdit"
        height="100%" width="100%" :cell-class-name="cellClassName" :size="tableModel.size" :stripe="tableModel.stripe"
        :border="tableModel.border">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column v-if="tableModel.index" type="index" label="行号" width="70" align="center" fixed />

        <template v-for="(item, index) in tableModel.columns" :key="index">
          <el-table-column v-if="item.show" :column-key="item.prop" :prop="item.prop" :width="item.width"
            :sortable="item.sortable" :fixed="item.fixed" :label="item.label" :formatter="item.formatter"
            :show-overflow-tooltip="item.showOverflowTooltip" align="center" />
        </template>
      </el-table>

      <!--  编辑框  -->
      <el-dialog v-model="editForm.show" :title="editForm.title" :close-on-click-modal="false" @close="handleClose"
        center append-to-body draggable>
        <el-form :ref="options.editForm.ref" :model="editForm.data" :rules="rules" label-width="100px">
          <el-form-item label="上级组织" prop="parentId">
            <el-input v-model="editForm.data.parentId" placeholder="请输入上级组织" />
          </el-form-item>
          <el-form-item label="组织编码" prop="code">
            <el-input v-model="editForm.data.code" placeholder="请输入组织编码" />
          </el-form-item>
          <el-form-item label="组织名称" prop="name">
            <el-input v-model="editForm.data.name" placeholder="请输入组织名称" />
          </el-form-item>
          <el-form-item label="组织状态" prop="state">
            <el-switch v-model="editForm.data.state" :active-value="1" :inactive-value="0" />
          </el-form-item>
          <el-form-item label="显示顺序" prop="orderNum">
            <el-input-number v-model="editForm.data.orderNum" :min="1" :max="99" controls-position="right" />
          </el-form-item>
        </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="handleSubmit" auto-insert-space>确定</el-button>
            <el-button @click="handleClose" auto-insert-space>取消</el-button>
          </div>
        </template>
      </el-dialog>
    </b-table>
  </div>
</template>

<script setup name="Org">
import { stateClassName } from '@/utils/formatter'
import {
  list,
  listExcelHeader,
  add,
  update,
  exportData,
  deleteData,
  fetchTree
} from '@/api/system/org'
import useCrud from '@/hook/useCrud'
import useTree from '@/hook/useTree'

const { proxy } = getCurrentInstance()

const treeOptions = {
  tree: {
    ref: 'treeRef',
    nodeKey: 'id',
    propConfig: { children: 'children', label: 'name' },
    click: {
      after: () => {
        queryModel.value.parentId = tree.clickNode.id
        // console.log(queryModel, tree, 'click after')
        handleQuery()
      }
    }
  },
  action: { query: { api: fetchTree } }
}
const {
  tree,
  filterText,
  fetchTree: fetchTreeData,
  filterTreeNode,
  expandAll,
  foldAll,
  clickNode
} = useTree(proxy, treeOptions)

const options = {
  model: {
    idProp: 'id',
    tipsProp: 'name',
  },
  view: {
    refreshView: () => {
      fetchTableData()
      fetchTreeData()
    }
  },
  queryForm: {
    ref: 'queryFormRef',
    params: { code: undefined, name: undefined, state: undefined }
  },
  table: {
    ref: 'tableRef',
    columnSettingRef: 'columnSettingRef',
    columnStoreKey: 'org',
    pageSizes: [100, 200, 500, 1000]
  },
  editForm: { ref: 'editFormRef', },
  action: {
    query: { api: list },
    delete: { api: deleteData },
    download: { api: exportData },
    upload: { api: undefined, fetchHeaderApi: listExcelHeader },
    add: { api: add },
    edit: { api: update },
  }
}
const {
  queryModel,
  tableModel,
  upload,
  loading,
  disabled,
  resetColumnSetting,
  saveColumnSetting,
  handleSelectionChange,
  handleHeaderCellClass,
  handleSortChange,
  handleQuery,
  resetQuery,
  fetchTableData,
  pageNumChange,
  pageSizeChange,
  clickTableRow,
  handleDelete,
  handleExport,
  handleUpload,
  closeUpload,
  handleFileUploadProgress,
  handleFileSuccess,
  submitUpload,

  editForm,
  handleAdd,
  handleEdit,
  handleSubmit,
  handleClose
} = useCrud(proxy, options)

const rules = {
  code: [{ required: true, message: '组织编码不能为空', trigger: 'blur' }]
}

function cellClassName(val) {
  // console.log(val)
  const columnKey = val.column.columnKey
  if (columnKey === 'state') {
    return stateClassName(val.row[columnKey])
  }
}

options.view.refreshView()
</script>
<style scoped lang="scss">
.view-container {
  display: flex;
  height: 100%;

  :deep(.org-tree) {
    .header {
      justify-content: space-between;
    }
  }

  .b-table {
    margin-left: 5px;
  }
}
</style>
